package cn.iocoder.yudao.module.system.controller.admin.patentapplication;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.CommonConstant;
import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils;
import cn.iocoder.yudao.module.system.controller.admin.patentapplication.vo.PatentApplicationNewRespVO;
import cn.iocoder.yudao.module.system.controller.admin.patentapplication.vo.PatentApplicationPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.patentapplication.vo.PatentApplicationRespVO;
import cn.iocoder.yudao.module.system.controller.admin.patentapplication.vo.PatentApplicationSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.casedata.CaseDO;
import cn.iocoder.yudao.module.system.dal.dataobject.patentapplication.PatentApplicationDO;
import cn.iocoder.yudao.module.system.dal.dataobject.permission.RoleDO;
import cn.iocoder.yudao.module.system.dal.dataobject.permission.UserRoleDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.dal.mysql.permission.UserRoleMapper;
import cn.iocoder.yudao.module.system.enums.sms.SmsSceneEnum;
import cn.iocoder.yudao.module.system.service.casedata.CaseService;
import cn.iocoder.yudao.module.system.service.patentapplication.PatentApplicationService;
import cn.iocoder.yudao.module.system.service.permission.RoleService;
import cn.iocoder.yudao.module.system.service.sms.SmsSendService;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;
import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.common.CommonConstant.PATENT_ADMIN;
import static cn.iocoder.yudao.framework.common.CommonConstant.PATENT_ORDINARY_ADMIN;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static java.util.Arrays.asList;


@Tag(name = "管理后台 - 会员专利申请")
@RestController
@RequestMapping("/system/patent-application")
@Validated
public class PatentApplicationController {

    @Resource
    private PatentApplicationService patentApplicationService;
    @Resource
    private AdminUserService adminUserService;
    @Resource
    private RoleService roleService;
    @Resource
    private UserRoleMapper userRoleMapper;
    @Resource
    private SmsSendService smsSendService;
    @Resource
    private CaseService caseService;
    @PostMapping("/create")
//    @Operation(summary = "创建会员专利申请")
    @PreAuthorize("@ss.hasPermission('system:patent-application:create')")
    public CommonResult<Long> createPatentApplication(@RequestBody PatentApplicationSaveReqVO createReqVO) {
        createReqVO.setReturnFiles(null);
        createReqVO.setUploadDate(null);
        List<String> reviewMaterialsFiles = createReqVO.getReviewMaterialsFiles();
        if(reviewMaterialsFiles.size()>10){
            throw exception(new ErrorCode(500,"审核文件不能超过10个"));
        }
        Long patentApplication = patentApplicationService.createPatentApplication(createReqVO);
        Boolean ifRemind=createReqVO.getIfRemind();
        if(patentApplication>0&&ifRemind){
            CaseDO aCase = caseService.getCase(createReqVO.getCaseId());
            if(ObjectUtil.isNull(aCase)){
                throw exception(new ErrorCode(500,"案件不存在"));
            }
            AdminUserDO user = adminUserService.getUser(aCase.getReviewerBy());
            if(ObjectUtil.isNull(user)){
                throw exception(new ErrorCode(500,"撰写人不存在"));
            }
            sendRemind(user.getMobile());
            patentApplicationService.updateRemindTime(patentApplication);
        }
        return success(patentApplication);
    }

    @PostMapping("/remind")
//    @Operation(summary = "创建会员专利申请")
    @PreAuthorize("@ss.hasPermission('system:patent-application:remind')")
    public CommonResult<Boolean> remindPatentApplication(@RequestBody PatentApplicationSaveReqVO createReqVO) {
        Long id = createReqVO.getId();
        if(ObjectUtil.isNull(id)){
            throw exception(new ErrorCode(500,"id不能为空"));
        }
        PatentApplicationDO patentApplication = patentApplicationService.getPatentApplication(id);
        if(ObjectUtil.isNull(patentApplication)){
            throw exception(new ErrorCode(500,"专利进度不存在"));
        }
        CaseDO aCase = caseService.getCase(patentApplication.getCaseId());
        if(ObjectUtil.isNull(aCase)){
            throw exception(new ErrorCode(500,"案件不存在"));
        }
        AdminUserDO user = adminUserService.getUser(aCase.getReviewerBy());
        if(ObjectUtil.isNull(user)){
            throw exception(new ErrorCode(500,"撰写人不存在"));
        }
        sendRemind(user.getMobile());
        patentApplicationService.updateRemindTime(id);
        return success(true);
    }
    public void sendRemind(String mobile){
    smsSendService.sendSingleSms(mobile, null, null,
    SmsSceneEnum.ADMIN_REMIND.getTemplateCode(), MapUtil.empty());
    }

    @PutMapping("/update")
//    @Operation(summary = "更新会员专利申请")
    @PreAuthorize("@ss.hasPermission('system:patent-application:update')")
    public CommonResult<Boolean> updatePatentApplication( @RequestBody PatentApplicationSaveReqVO updateReqVO) {
        updateReqVO.setUploadDate(null);
        updateReqVO.setReturnFiles(null);
        List<String> reviewMaterialsFiles = updateReqVO.getReviewMaterialsFiles();
        if(reviewMaterialsFiles.size()>10){
            throw exception(new ErrorCode(500,"审核文件不能超过10个"));
        }
//        Long caseId = updateReqVO.getCaseId();
//        if(ObjectUtil.isNull(caseId)){
//            throw exception(new ErrorCode(500,"案件id不能为空"));
//        }
//        CaseDO aCase = caseService.getCase(caseId);
//        if(ObjectUtil.isNull(aCase)){
//            throw exception(new ErrorCode(500,"案件id错误"));
//        }
        patentApplicationService.updatePatentApplication(updateReqVO);
        if(updateReqVO.getIfRemind()){
            CaseDO aCase = caseService.getCase(updateReqVO.getCaseId());
            if(ObjectUtil.isNull(aCase)){
                throw exception(new ErrorCode(500,"案件不存在"));
            }
            AdminUserDO user = adminUserService.getUser(aCase.getReviewerBy());
            if(ObjectUtil.isNull(user)){
                throw exception(new ErrorCode(500,"撰写人不存在"));
            }
            patentApplicationService.updateRemindTime(updateReqVO.getId());


        }
        return success(true);
    }

    @DeleteMapping("/delete")
//    @Operation(summary = "删除会员专利申请")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('system:patent-application:delete')")
    public CommonResult<Boolean> deletePatentApplication(@RequestParam("id") Long id) {
        patentApplicationService.deletePatentApplication(id);
        return success(true);
    }


    @GetMapping("/export-excel")
//    @Operation(summary = "导出会员专利申请 Excel")
    @PreAuthorize("@ss.hasPermission('member:patent-application:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportPatentApplicationExcel( PatentApplicationPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        // 导出 Excel
        ExcelUtils.write(response, "会员专利申请.xls", "数据", PatentApplicationRespVO.class,
        BeanUtils.toBean(patentApplicationService.getPatentApplicationPage(pageReqVO).getList(), PatentApplicationRespVO.class));
    }


    @GetMapping("/get")
//    @Operation(summary = "获得会员专利申请")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:patent-application:query')")
    public CommonResult<PatentApplicationNewRespVO> findPatentApplicationDetail(@RequestParam("id") Long id) {
        return success(patentApplicationService.findPatentApplicationDetail(id));
    }

    @GetMapping("/page")
//    @Operation(summary = "获得会员专利申请分页")
    @PreAuthorize("@ss.hasPermission('system:patent-application:query')")
    public CommonResult<PageResult<PatentApplicationNewRespVO>> findPatentApplicationPage(@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
        @RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize, @RequestParam(value = "caseName",required = false) String caseName){
        Long loginUserId=WebFrameworkUtils.getLoginUserId();
        Long reviewerBy=null;
        if(loginUserId!=1){
        List<Long>roleIds=userRoleMapper.selectListByUserId(loginUserId).stream().map(UserRoleDO::getRoleId).collect(Collectors.toList());
        if(roleIds.isEmpty()){throw exception(new ErrorCode(500,"无权限访问"));}
        List<String>adminKeys=asList(PATENT_ORDINARY_ADMIN,PATENT_ADMIN);
        Set<String>roleKeys=roleService.getRoleListFromCache(roleIds).stream().filter(role->adminKeys.contains(role.getCode())).map(RoleDO::getCode).collect(Collectors.toSet());
        if(roleKeys.isEmpty()){throw exception(new ErrorCode(500,"无权限访问"));}
        reviewerBy=loginUserId;
        if(roleKeys.contains(PATENT_ADMIN)){reviewerBy=null;}
        }
        return success(patentApplicationService.findPatentApplicationPage(pageNum, pageSize, caseName,reviewerBy,null));
    }


    @PutMapping("/upload-return-files")
//    @Operation(summary = "更新会员专利申请")
    @PreAuthorize("@ss.hasPermission('system:patent-application:upload-return-files')")
    public CommonResult<Boolean> uploadReturnFiles(@RequestBody PatentApplicationSaveReqVO updateReqVO) {
        patentApplicationService.uploadReturnFiles(updateReqVO);
        return success(true);
    }

}